/*
 * Copyright (C), 2002-2016, 苏宁易购电子商务有限公司
 * FileName: BatchTransferData.java
 * Author:   16031333
 * Date:     2016年5月25日 上午10:30:43
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.hl.toolkit.server.suning.dto;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suning.SuNingConfig;
import com.suning.epps.codec.Digest;
import com.suning.epps.codec.RSAUtil;
import com.suning.util.HttpClientUtil;

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 批量出款 数据拼写
 * 
 * @author 16031333
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class BatchWithdrawData {

	private String publicKeyIndex = "0001";
	private String signAlgorithm = "RSA";
 	private String inputCharset = "UTF-8";

 	private  String  BatchNo;

	/**
	 * 请求转账网关
	 * 
	 * @param baseUrl
	 *            请求业务数据 batchNum 请求的批次数目 detailNum 单批次中的明细数目
	 * @param bankCode
	 * @param receiverCardNo
	 * @param bankName
	 * @param amount
	 * @param receiverName
	 * @return signature 签名
	 * @throws UnsupportedEncodingException
	 * @throws InvalidKeyException
	 * @throws KeyManagementException
	 * @see [相关类/方法]（可选）
	 * @since [产品/模块版本] （可选）
	 */
	public String batchWithDraw(String baseUrl, String receiverName, String amount, String bankName,
			String receiverCardNo, String bankCode,String batchNo)
			throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException,
			UnsupportedEncodingException, InvalidKeyException, KeyManagementException {

		this.BatchNo=batchNo;

		String bussinessParam = createBatchData(1, 1,  receiverName,   amount,   bankName,
				  receiverCardNo,   bankCode).toJSONString();
		String singnature = calculateSign(bussinessParam);
		String responseStr = HttpClientUtil.post(publicKeyIndex, signAlgorithm, SuNingConfig.merchantNo, inputCharset, baseUrl,
				singnature, bussinessParam);
		return responseStr;
	}

	/**
	 * 计算签名
	 *
	 * @param body
	 *            请求业务数据
	 * @return signature 签名
	 * @throws InvalidKeyException
	 * @see [相关类/方法]（可选）
	 * @since [产品/模块版本] （可选）
	 */
	public String calculateSign(String body) throws NoSuchAlgorithmException, InvalidKeySpecException,
			InvalidKeyException, SignatureException, InvalidKeyException {
		Map<String, String> signMap = new HashMap<String, String>();
		signMap.put("merchantNo", SuNingConfig.merchantNo);
		signMap.put("publicKeyIndex", publicKeyIndex);
		signMap.put("inputCharset", "UTF-8");
		signMap.put("body", body);
		// String wagKeyString =
		// "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALEhTthjWVcdzYkbrzW1eydORboUQPkWpuf_Phy9b3tt4Vz8wweI0cwGjB8owJIV_vLnNB-zikCWUOaaeey3MlrxqxKVqtI1GWWVJnTD7fcH_3JUo8Qs97AWoS869JRloDZADxFqHdcixr6n8W-N0fqjb43Fzp0LCZ6gABVb_38DAgMBAAECgYB3zVVsmdWFTI0FnQnmQ7bmINScRLKlRqLg6wvxmFbcnrb8k6C9adasLgl70a5doC7tz167yk1J3eEd94Fbj5SoNlZSYJvnA6eIKJ3LJtShAZLDed4PW4zNkcRqDMRSJrOgrjYVVs_XqOmvTFELyiCjxQtzhn0RR8rM0-10u7HfsQJBAPpFnF66jGVVpRpU2tmRtJwW6E6ScB_IxEhkwgcgZjLIyR18xxPE4kXLUh9ihfZSlsuMFfUp1njEYUDqSZ__BF0CQQC1LyVXmkGWKGIkxvnRaXaDrmLupTesaO8p4Uq9Wa3aGR6CggGhqc8rLFQpSRB0EaKT0wQ0HZYuH-1X6RQ1elrfAkEAuECxe8hJfn1MPROFv7IWzufKhbYn2C6d21JaypZexzqtXgk0I2jK0Wl7_2EwkQWCwT5UGBeCL40csIcMRz-ffQJARfPw7_Svs-Ddm6NzGoYkaszuh4Mkjp1pEXtZVugD9nvSSsMVDCy6vsl7qQD7qESSx44mRlTSAfbztQhZdBhMcwJABElZOJE1O4WHvjhzniLh5X1RelimfWOIubqDMtoP9o5iVhOwBK0B9kG4KxSagUvNNTQ2iIKeyzda0us4Ydf2mQ";
		String digest = Digest.digest(Digest.mapToString(Digest.treeMap(signMap)));
		// PrivateKey privateKey = RSAUtil.getPrivateKey(wagKeyString);
		PrivateKey privateKey = RSAUtil.resolvePrivateKey("D:/RSA/private.key");

		String signature = RSAUtil.sign(digest, privateKey);
		return signature;
	}

	/**
	 * 生成请求wag多个批次的json数据方法
	 * 
	 * @param batchNum
	 *            请求批次数目
	 * @return JSONArray
	 * @see [相关类/方法]（可选）
	 * @since [产品/模块版本] （可选）
	 */
	public JSONArray createBatchData(int batchNum, int detailNum,
                                     String receiverName, String amount, String bankName,
                                     String receiverCardNo, String bankCode
			) {
		JSONArray jsonArray = new JSONArray();
		if (batchNum > 0) {
			for (int i = 0; i < batchNum; i++) {
				jsonArray.add(bulidBatchContentJosn(detailNum,
						  receiverName,   amount,   bankName,
						  receiverCardNo,   bankCode));
			}
		}
		return jsonArray;
	}

	/**
	 * 生成body批次数据
	 * 
	 * @param
	 * @return JSONObject
	 * @see [相关类/方法]（可选）
	 * @since [产品/模块版本] （可选）
	 */
	public JSONObject bulidBatchContentJosn(int detailNum,
                                            String receiverName, String amount, String bankName,
                                            String receiverCardNo, String bankCode
			) {

		JSONObject contentObject = new JSONObject();
		contentObject.put("batchNo", BatchNo);
		contentObject.put("merchantNo", SuNingConfig.merchantNo);// 70057241;70056575
		contentObject.put("productCode", "01070000042");
		contentObject.put("totalNum", detailNum);
		contentObject.put("totalAmount", Integer.valueOf(amount)* detailNum);// 40*detailNum
		contentObject.put("currency", "CNY");
		contentObject.put("payDate", "20170524");
		contentObject.put("tunnelData", "{\"businessOrderId\":\"aaaaaaaaaaxxxxxxaaaaabe\"}");
		contentObject.put("goodsType", "220029");
		contentObject.put("remark", "这是一个demo");
		contentObject.put("productCode", "01070000042");
		contentObject.put("detailData", bulidDetailContentJosn(detailNum,
				  receiverName,   amount,   bankName,
				  receiverCardNo,   bankCode
				));
		contentObject.put("notifyUrl", SuNingConfig.applicationNotiyReturnUrl);
		contentObject.put("batchOrderName", "批量出款");
		return contentObject;
	}

	/**
	 * 生成body明细数据
	 * 
	 * @param
	 * @return JSONObject
	 * @see [相关类/方法]（可选）
	 * @since [产品/模块版本] （可选）
	 */
	public JSONArray bulidDetailContentJosn(int detailNum,
                                            String receiverName, String amount, String bankName,
                                            String receiverCardNo, String bankCode) {
		JSONArray detailArray = new JSONArray();
		for (int i = 0; i < detailNum; i++) {
			JSONObject detailObject = new JSONObject();
			detailObject.put("serialNo", BatchNo);
			detailObject.put("receiverType", "PERSON");
			detailObject.put("receiverCurrency", "CNY");
			detailObject.put("receiverName",receiverName);
			detailObject.put("amount", amount);
			detailObject.put("orderName", "煌亦全");
			detailObject.put("bankName", bankName);
			detailObject.put("receiverCardNo", receiverCardNo);
			detailObject.put("bankCode", bankCode);
			detailObject.put("bankProvince", "");
			detailObject.put("bankCity", "");
			detailObject.put("payeeBankLinesNo", "");
			detailArray.add(detailObject);
		}
		return detailArray;

	}

}
